package com.rc.saas.tenant.controller.invoice;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.invoice.InvoiceApply;
import com.rc.saas.tenant.model.invoice.InvoiceOrder;
import com.rc.saas.tenant.model.msg.TenantNotice;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.model.rc.RcOperatorAccount;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.msg.TenantNoticeSearch;
import com.rc.saas.tenant.service.invoice.InvoiceApplyService;
import com.rc.saas.tenant.search.invoice.InvoiceSearch;
import com.rc.saas.tenant.service.invoice.InvoiceOrderService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.invoice.InvoiceApplyPrintVo;
import com.rc.saas.tenant.vo.invoice.InvoiceApplyResultVo;
import com.rc.saas.tenant.vo.invoice.InvoiceApplyVo;
import com.rc.saas.tenant.vo.order.OrderPrintVo;
import com.rc.saas.tenant.vo.order.OrderResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author frog
 * @date 2021/3/19
 */
@Controller
@RequestMapping("/invoiceApply")
public class InvoiceApplyController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private InvoiceApplyService invoiceApplyService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private InvoiceOrderService invoiceOrderService;

    @Autowired
    private TenantRoleService tenantRoleService;

    /**
     * 跳转发票页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        model.addAttribute("user", user);
        return "/templates/invoice/invoiceApply";
    }


    /**
     * 返回发票列表数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listPageInvoiceApply", method = RequestMethod.GET)
    public WebPageInfo listPageInvoiceApply(InvoiceSearch invoiceSearch) {
        //获取登陆人信息
        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole role = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        String dataAuth = role.getDataAuth();//数据权限 100 平台权限, 010 加盟商权限,001企业权限,111全部权限 默认111 不能为000
        String roleType = role.getRoleType();//角色类型 ( 0 超级管理员 1 普通用户 2加盟商 3企业用户) 默认1`
        invoiceSearch.setDataAuth(dataAuth);
        invoiceSearch.setRoleType(roleType);
        invoiceSearch.setBaseOperatorId(user.getOperatorId());
        invoiceSearch.setBaseEnterpriseId(user.getEnterpriseId());

        PageInfo<InvoiceApplyResultVo> pageInfo = invoiceApplyService.listPageInvoiceApply(invoiceSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出发票列表
     */
    @ResponseBody
    @RequestMapping("/exportInvoiceApply")
    public TResponse exportInvoiceApply(InvoiceSearch invoiceSearch, HttpServletResponse response) throws Exception {
        //导出拼接开始条数
        ExportUtils.setDefaultPaging(invoiceSearch);
        invoiceSearch.setOffset(invoiceSearch.getLimit() * (invoiceSearch.getOffset() - 1));
        List<InvoiceApplyPrintVo> list = invoiceApplyService.exportInvoiceApply(invoiceSearch);
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("发票信息列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), InvoiceApplyPrintVo.class).sheet("发票信息列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出发票信息列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }

    }


    /**
     * 导出发票订单列表
     */
    @ResponseBody
    @RequestMapping("/exportInvoiceOrder")
    public void exportInvoiceOrder(Long invoiceApplyId, HttpServletResponse response) throws Exception {
        List<OrderPrintVo> orderPrintVos = invoiceApplyService.exportInvoiceOrder(invoiceApplyId);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderPrintVo.class).sheet("订单列表").doWrite(orderPrintVos);
        } catch (Exception e) {
            logger.error("导出订单失败", e.getMessage());
        }
    }


    /**
     * 发票审核通过/
     *
     * 驳回
     */
    @ResponseBody
    @RequestMapping(value = "/review", method = RequestMethod.POST)
    public TResponse saveReview(Long invoiceApplyId, String status) {
        try {
            //status  0:通过 1:驳回
            invoiceApplyService.saveReview(invoiceApplyId, status);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("发票审核失败", e);
            return TResponse.FAIL("发票审核失败");
        }
    }

    @RequestMapping("/add")
    public String add() {
        return "/templates/invoice/addInvoiceApply";
    }

    @RequestMapping("/detail/{id}")
    public String detail(Model model, @PathVariable("id") Long id) {
        InvoiceApply invoiceApply = invoiceApplyService.selectByKey(id);
        model.addAttribute("invoiceApply", invoiceApply);
        return "/templates/invoice/detailInvoiceApply";
    }

    @ResponseBody
    @RequestMapping("/addInvoiceApply")
    public TResponse addInvoiceApply(@RequestBody InvoiceApplyVo vo) {
        OrderInfo orderInfo = orderInfoService.selectOrderByOrderNum(vo.getOrderNum());

        if (orderInfo == null) {
            return TResponse.FAIL("找不到充电订单");
        }
        invoiceApplyService.addInvoiceApply(vo.getInvoiceApply(), vo.getOrderNum());
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/listOrderWithInvocieApply")
    public WebPageInfo listOrderWithInvocieApply(Long invoiceApplyId) {
        PageInfo<OrderResult> pageInfo = invoiceOrderService.listOrderByInvoiceApply(invoiceApplyId);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 导出开票申请列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(InvoiceSearch invoiceSearch, HttpServletResponse response) {
        try {
            //获取登陆人信息
            TenantUser user = ShiroUtils.getSessionUser();
            TenantRole role = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
            String dataAuth = role.getDataAuth();//数据权限 100 平台权限, 010 加盟商权限,001企业权限,111全部权限 默认111 不能为000
            String roleType = role.getRoleType();//角色类型 ( 0 超级管理员 1 普通用户 2加盟商 3企业用户) 默认1`
            invoiceSearch.setDataAuth(dataAuth);
            invoiceSearch.setRoleType(roleType);
            invoiceSearch.setBaseOperatorId(user.getOperatorId());
            invoiceSearch.setBaseEnterpriseId(user.getEnterpriseId());

            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(invoiceSearch);
            PageInfo<InvoiceApplyResultVo> page = invoiceApplyService.listPageInvoiceApply(invoiceSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("开票申请列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), InvoiceApplyResultVo.class).sheet("开票申请列表").doWrite(page.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出开票申请列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


}
